package com.turing.mission.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.turing.mission.entity.Mission;
import com.turing.mission.entity.MyMission;
import com.turing.mission.feign.*;
import com.turing.mission.mapper.MyMissionMapper;
import com.turing.mission.service.MissionService;
import com.turing.mission.mapper.MissionMapper;
import com.turing.mission.service.MyMissionService;
import enums.ErrorCode;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import result.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @author dell
* @description 针对表【mission(任务)】的数据库操作Service实现
* @createDate 2023-05-08 22:36:13
*/
@Service
public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission>
    implements MissionService{

    @Resource
    private AuthService authService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CustomerService customerService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private MerchantService merchantService;
    @Resource
    private WithdrawalService withdrawalService;
    @Resource
    private MyMissionMapper myMissionMapper;

    @Override
    public Result miList(String startTime, String endTime, String merchantName, String longitude, String latitude, String cityId, String merchantId, String mtId, Integer sortType, Integer orderType, Integer pageNum, Integer pageSize) {
        //获取token
        String token = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        token = token.substring(tokenHead.length());
        System.out.println("token = " + token);
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        String username = jsonObject.getString("username");
        int type = 0;
        Result result = customerService.geCusById(username);
        if(result.getData() != null ){
            type = 1;
        }

        if (pageNum!=null && pageSize!=null){
            PageHelper.startPage(pageNum,pageSize);
        }
        List<String> misIds = new ArrayList<>();
        Map redisData = new HashMap();
        ZSetOperations zsetOps = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple> redisSet;
        if (sortType == 5){
            if (pageNum!=null){
                if (orderType==1){
                    redisSet = zsetOps.reverseRangeWithScores("missionComments", (pageNum - 1) * pageSize, pageNum * pageSize - 1);
                }else{
                    redisSet = zsetOps.rangeWithScores("missionComments", (pageNum - 1) * pageSize, pageNum * pageSize - 1);
                }
            }else{
                if (orderType==1){
                    redisSet = zsetOps.reverseRangeWithScores("missionComments", 0, -1);
                }else{
                    redisSet = zsetOps.rangeWithScores("missionComments", 0, -1);
                }
            }
            for (ZSetOperations.TypedTuple typedTuple : redisSet) {
                misIds.add((String) typedTuple.getValue());
            }
        }else{
            redisSet = zsetOps.rangeWithScores("missionComments", 0, -1);
            for (ZSetOperations.TypedTuple typedTuple : redisSet) {
                redisData.put(typedTuple.getValue(), typedTuple.getScore());
            }
        }
        List<Map> list = this.baseMapper.miList(startTime,endTime,merchantName,longitude,latitude,cityId,merchantId,mtId,sortType,orderType,username,misIds,type);
        if (sortType != 5){
            for (Map map : list) {
                map.put("missionComments",redisData.get(map.get("missionId")));
            }
        }

        if(pageNum!=null && pageSize!=null){
            return Result.success(new PageInfo<>(list));
        }
        return Result.success(list);
    }

    @Override
    public Result geMissionById(String id) throws ParseException {
        if(id != null && id != ""){
            Mission mission = this.baseMapper.selectById(id);
            return Result.success(mission);
        }else {
            List<Mission> list = list();
            return Result.success(list);
        }
    }

    @Override
    public Result missonEdit(JSONObject jsonObject) {
        String missionId = jsonObject.getString("missionId");
        Double missonAmount = jsonObject.getDouble("missonAmount");
        Double singleMax = jsonObject.getDouble("singleMax");
        Integer sourceType = jsonObject.getInteger("sourceType");
        Mission mission = JSONObject.toJavaObject(jsonObject, Mission.class);
        if(missonAmount != null){
            mission.setMissionAmount(BigDecimal.valueOf(missonAmount));
        }
        if(singleMax != null){
            mission.setSingleMax(BigDecimal.valueOf(singleMax));
        }
        System.out.println("mission = " + mission);
        //判断任务是否开始
        if(this.baseMapper.selectById(missionId).getStartTime().before(new Date())){
            return Result.fail(2,"任务已开始！");
        }
        Mission mission1 = this.baseMapper.selectById(missionId);
        System.out.println("mission1 = " + mission1);
        //sourceType是否改变
        System.out.println("!sourceType.equals(mission1.getSourceType()) = " + !sourceType.equals(mission1.getSourceType()));
        if(!sourceType.equals(mission1.getSourceType())){
            if(sourceType==0){
                //商家
                Result result = merchantService.getMerById(mission1.getMerchantId());
                System.out.println("result = " + result);
                JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(result.getData()));
                Result result1 = dictionaryService.getDic("26", "平台账户");
                JSONObject jsonObject5 = JSON.parseObject(JSON.toJSONString(result1.getData()));
                if(jsonObject2.getDouble("totalAmount")-jsonObject2.getDouble("sendAmount") < (missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue())){
                    return Result.fail(2,"商家余额不足！");
                }else {
                    //退还平台金额
                    JSONObject jsonObject4 = new JSONObject();
                    jsonObject4.put("dicId",26);
                    if((missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue())==(mission1.getMissionAmount().doubleValue())){
                        //赏金金额不变
                        jsonObject4.put("dicInfo",Double.parseDouble(jsonObject5.getString("dicInfo"))+mission1.getMissionAmount().doubleValue());
                    }else {
                        //赏金金额改变
                        jsonObject4.put("dicInfo",Double.parseDouble(jsonObject5.getString("dicInfo"))+missonAmount.doubleValue());
                    }
                    dictionaryService.editSave(jsonObject4);

                    //修改商家的已发赏金
                    if(jsonObject.getString("merchantId").isEmpty()){
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("merchantId",mission1.getMerchantId());
                        jsonObject1.put("sendAmount",jsonObject2.getDouble("sendAmount") + (missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue()));
                        merchantService.merEdit(jsonObject1);
                    }else{
                        if(jsonObject.getString("merchantId").equals(mission1.getMerchantId())){
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("merchantId",mission1.getMerchantId());
                            jsonObject1.put("sendAmount",jsonObject2.getDouble("sendAmount") + (missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue()));
                            merchantService.merEdit(jsonObject1);
                        }else {
                            JSONObject jsonObject6 = new JSONObject();
                            jsonObject6.put("merchantId",mission1.getMerchantId());
                            jsonObject6.put("sendAmount",jsonObject2.getDouble("sendAmount") - mission1.getMissionAmount().doubleValue());
                            merchantService.merEdit(jsonObject6);

                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("merchantId",jsonObject.getString("merchantId"));
                            jsonObject1.put("sendAmount",jsonObject2.getDouble("sendAmount") + (missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue()));
                            merchantService.merEdit(jsonObject1);
                        }
                    }

                    //增加商家流水
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("kwInfo",jsonObject2.getString("merchantName")+","+"任务修改退回");
                    jsonObject3.put("sourceId",mission1.getMerchantId());
                    jsonObject3.put("targetId",null);
                    jsonObject3.put("kwValue",(missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue()));
                    jsonObject3.put("kwType",0);
                    jsonObject3.put("kwCreateTime",new Date());
                    jsonObject3.put("sourceReValue",jsonObject2.getDouble("totalAmount")-jsonObject2.getDouble("sendAmount"));
                    withdrawalService.kwAddSave(jsonObject3);
                }

            }else {
                //平台
                Result result = dictionaryService.getDic("26", "平台账户");
                JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(result.getData()));
                Result result1 = merchantService.getMerById(mission1.getMerchantId());
                JSONObject jsonObject4 = JSON.parseObject(JSON.toJSONString(result1.getData()));
                if(Double.parseDouble(jsonObject2.getString("dicInfo")) < (missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue())){
                    return Result.fail(3,"平台余额不足！");
                }else {
                    //退还商家赏金
                    JSONObject jsonObject5 = new JSONObject();
                    jsonObject5.put("merchantId",mission1.getMerchantId());
                    if((missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue())==(mission1.getMissionAmount().doubleValue())){
                        //赏金金额不变
                        jsonObject5.put("sendAmount",jsonObject4.getDouble("sendAmount") - mission1.getMissionAmount().doubleValue());
                    }else {
                        //赏金金额改变
                        jsonObject5.put("sendAmount",jsonObject4.getDouble("sendAmount") - missonAmount.doubleValue());
                    }
                    merchantService.merEdit(jsonObject5);
                    //修改字典表中的"平台账户"
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("dicId",26);
                    jsonObject1.put("dicInfo",Double.parseDouble(jsonObject2.getString("dicInfo"))-(missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue()));
                    dictionaryService.editSave(jsonObject1);
                    //增加商家流水
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("kwInfo","任务修改退回");
                    jsonObject3.put("targetId",mission1.getMerchantId());
                    jsonObject3.put("kwType",0);
                    jsonObject3.put("sourceId",null);
                    jsonObject3.put("targetReValue",Double.parseDouble(jsonObject2.getString("dicInfo")));
                    jsonObject3.put("kwValue",(missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue()));
                    jsonObject3.put("kwCreateTime",new Date());
                    withdrawalService.kwAddSave(jsonObject3);
                }
            }
        }else{
            Result result = merchantService.getMerById(mission1.getMerchantId());
            JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(result.getData()));
            Result result1 = dictionaryService.getDic("26", "平台账户");
            JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(result1.getData()));
            if(sourceType==0) {
                //商家
                JSONObject jsonObject5 = new JSONObject();
                jsonObject5.put("merchantId",mission1.getMerchantId());
                if((missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue())!=(mission1.getMissionAmount().doubleValue())){
                    //赏金金额改变
                    double amount = missonAmount.doubleValue() - mission1.getMissionAmount().doubleValue();
                    jsonObject5.put("sendAmount",jsonObject1.getDouble("sendAmount") + amount);
                    merchantService.merEdit(jsonObject5);
                }

            }else {
                //改变平台金额
                JSONObject jsonObject4 = new JSONObject();
                jsonObject4.put("dicId",26);
                System.out.println((missonAmount != null ? missonAmount.doubleValue() : mission1.getMissionAmount().doubleValue()) != (mission1.getMissionAmount().doubleValue()));
                if((missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue())!=(mission1.getMissionAmount().doubleValue())){
                    //赏金金额改变
                    double amount = missonAmount.doubleValue() - mission1.getMissionAmount().doubleValue();
                    System.out.println("amount = " + amount);
                    jsonObject4.put("dicInfo",Double.parseDouble(jsonObject2.getString("dicInfo"))-amount);
                    dictionaryService.editSave(jsonObject4);
                }
            }
        }
        mission.setLeftAmount(BigDecimal.valueOf(missonAmount != null?missonAmount.doubleValue():mission1.getMissionAmount().doubleValue()));
        int i = this.baseMapper.updateById(mission);
        if(i > 0){
            return Result.success();
        }
        return Result.fail(ErrorCode.ERROR_EDIT);
    }

    @Override
    public Result missonSave(JSONObject jsonObject) {
        String merchantId = jsonObject.getString("merchantId");
        Double missonAmount = jsonObject.getDouble("missonAmount");
        Double singleMax = jsonObject.getDouble("singleMax");

        Mission mission = JSONObject.toJavaObject(jsonObject, Mission.class);
        mission.setLeftAmount(BigDecimal.valueOf(missonAmount));
        mission.setMissionAmount(BigDecimal.valueOf(missonAmount));
        mission.setSingleMax(BigDecimal.valueOf(singleMax));
        if(mission.getSourceType()==0){
            Result result = merchantService.getMerById(mission.getMerchantId());
            JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(result.getData()));
            if(jsonObject2.getDouble("totalAmount")-jsonObject2.getDouble("sendAmount") < missonAmount.doubleValue()){
                return Result.fail(2,"商家余额不足！");
            }else {
                //修改商家的已发赏金
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("merchantId",merchantId);
                jsonObject1.put("sendAmount",jsonObject2.getDouble("sendAmount") + missonAmount.doubleValue());
                merchantService.merEdit(jsonObject1);
                //增加商家流水
                JSONObject jsonObject3 = new JSONObject();
                jsonObject3.put("kwInfo","发布悬赏任务");
                jsonObject3.put("sourceId",merchantId);
                jsonObject3.put("kwValue",missonAmount.doubleValue());
                jsonObject3.put("kwType",0);
                jsonObject3.put("kwCreateTime",new Date());
                jsonObject3.put("sourceReValue",jsonObject2.getDouble("totalAmount")-jsonObject2.getDouble("sendAmount"));
                withdrawalService.kwAddSave(jsonObject3);
            }

        }else{
            Result result = dictionaryService.getDic("26", "平台账户");
            JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(result.getData()));
            Result result1 = merchantService.getMerById(merchantId);
            JSONObject jsonObject4 = JSON.parseObject(JSON.toJSONString(result1.getData()));
            if(Double.parseDouble(jsonObject2.getString("dicInfo")) <missonAmount.doubleValue()){
                return Result.fail(3,"平台余额不足！");
            }else {
                //修改字典表中的"平台账户"
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("dicId",26);
                jsonObject1.put("dicInfo",Double.parseDouble(jsonObject2.getString("dicInfo"))-missonAmount.doubleValue());
                dictionaryService.editSave(jsonObject1);
                //增加商家流水
                JSONObject jsonObject3 = new JSONObject();
                jsonObject3.put("kwInfo",jsonObject4.getString("merchantName")+"商家,"+"平台发布悬赏任务");
                jsonObject3.put("targetId",merchantId);
                jsonObject3.put("kwType",0);
                jsonObject3.put("sourceId",null);
                jsonObject3.put("targetReValue",Double.parseDouble(jsonObject2.getString("dicInfo")));
                jsonObject3.put("kwValue",missonAmount.doubleValue());
                jsonObject3.put("kwCreateTime",new Date());
                withdrawalService.kwAddSave(jsonObject3);
            }
        }
        int i = this.baseMapper.insert(mission);
        if(i > 0){
            return Result.success();
        }
        return Result.fail(ErrorCode.ERROR_ADD);
    }

    @Override
    public Result missonFreeze(JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        Mission mission = this.baseMapper.selectById(id);
        System.out.println("mission = " + mission);
        //任务的同步锁
        ValueOperations stringOps = redisTemplate.opsForValue();
        Long now = System.currentTimeMillis();
        //5秒内不断尝试获得锁
        while (System.currentTimeMillis()<(now+5000)){
            if(stringOps.setIfAbsent("missionId::"+id,"1",3, TimeUnit.SECONDS)){
                mission.setMissionState("N");
                this.baseMapper.updateById(mission);
                //释放锁
                redisTemplate.delete("missionId::"+id);
                break;
            }
        }

        Result result = merchantService.getMerById(mission.getMerchantId());
        JSONObject merchant = JSON.parseObject(JSON.toJSONString(result.getData()));
        Result result1 = dictionaryService.getDic("26", "平台账户");
        JSONObject dictionary = JSON.parseObject(JSON.toJSONString(result1.getData()));
        if(mission.getSourceType()==0){
            //退还商家的剩余赏金
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("merchantId",mission.getMerchantId());
            jsonObject1.put("sendAmount",merchant.getDouble("sendAmount") - mission.getLeftAmount().doubleValue());
            merchantService.merEdit(jsonObject1);
            //增加商家流水
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("kwInfo","任务关闭退款");
            jsonObject3.put("sourceId",mission.getMerchantId());
            jsonObject3.put("kwValue",mission.getLeftAmount().doubleValue());
            jsonObject3.put("kwType",0);
            jsonObject3.put("kwCreateTime",new Date());
            jsonObject3.put("sourceReValue",merchant.getDouble("totalAmount")-merchant.getDouble("sendAmount"));
            withdrawalService.kwAddSave(jsonObject3);
        }else {
            //退还字典表中的"平台账户"的剩余赏金
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("dicId",26);
            jsonObject1.put("dicInfo",Double.parseDouble(dictionary.getString("dicInfo")) + mission.getLeftAmount().doubleValue());
            dictionaryService.editSave(jsonObject1);
            //增加商家流水
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("kwInfo",merchant.getString("merchantName")+"商家,"+"任务关闭退款");
            jsonObject3.put("targetId",mission.getMerchantId());
            jsonObject3.put("kwType",0);
            jsonObject3.put("sourceId",null);
            jsonObject3.put("targetReValue",Double.parseDouble(dictionary.getString("dicInfo")));
            jsonObject3.put("kwValue",mission.getLeftAmount().doubleValue());
            jsonObject3.put("kwCreateTime",new Date());
            withdrawalService.kwAddSave(jsonObject3);
        }

        return Result.success();
    }

    @Override
    public Result missionGoodState(String missionId) {
        //获取token
        String token = request.getHeader("Authorization");

        System.out.println("missionId = " + missionId);
        Mission mission = this.baseMapper.selectById(missionId);
        if(mission.getGdId() == null){
            return Result.success(0);
        }
        Result result = merchantService.geGoodById(mission.getGdId());
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));
        if(jsonObject.getInteger("gdState") == 1){
            return Result.success(1);
        }

        Result result1 = merchantService.myGoodList(token,mission.getMerchantId(), mission.getGdId(), null,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mission.getStartTime()),null, null);
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(result1.getData()));
        System.out.println("array = " + array);
        for (Object map : array) {
            Map m = (Map) map;
            if("0".equals(m.get("myBuyCount").toString())){
                return Result.success(2);
            }
            if(Integer.valueOf(m.get("unConsumeCount").toString()) > 0){
                return Result.success(3);
            }
            if(Integer.valueOf(m.get("consumeCount").toString()) > 0){
                return Result.success(4);
            }
        }
        return Result.fail(6,"输入有误");
    }

    @Override
    public Result missonSign(JSONObject jsonObject) throws ParseException {
        String merchantId = jsonObject.getString("merchantId");
        String longitude = jsonObject.getString("longitude");
        String latitude = jsonObject.getString("latitude");
        //获取token
        String token = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        token = token.substring(tokenHead.length());
        System.out.println("token = " + token);
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject11 = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        String cusId = jsonObject11.getString("username");
        //距离是否超过500米
         Double distance = this.baseMapper.selectDis(longitude,latitude,merchantId);
         if(distance >500){
             return Result.fail(2,"距离超过500米，打卡失败");
         }
         //该商家的所有打卡任务
        List<String> missions = this.baseMapper.selectMiId(merchantId);
        System.out.println("missions = " + missions);
        if(missions.size()==0){
            return Result.fail(2,"该商家无任务");
        }
        //未打卡任务
        LambdaQueryWrapper<MyMission> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(MyMission::getCusId,cusId)
                .eq(MyMission::getSignState,0)
                .in(MyMission::getMissionId,missions);
        List<MyMission> myMissions = myMissionMapper.selectList(wrapper1);

        //客户当天在这个商家是否进行过打卡
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        LambdaQueryWrapper<MyMission> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.select(MyMission::getMissionId)
                .ge(MyMission::getSignDate,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date +" 00:00:00"))
                .le(MyMission::getSignDate,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date +" 23:59:59"))
                .in(MyMission::getMissionId,missions);
        List<MyMission> list1 = myMissionMapper.selectList(wrapper2);

        if(list1.size() == 0){
            Result result = customerService.geCusById(cusId);
            JSONObject customer = JSON.parseObject(JSON.toJSONString(result.getData()));
            String cusPrestige = customer.getString("cusPrestige");
            Integer kgCoin = customer.getInteger("kgCoin");
            Result result1;
            if(Double.parseDouble(cusPrestige) > 4.1){
                result1 = dictionaryService.getDic("8","三级用户");
            }else if(Double.parseDouble(cusPrestige) >= 2.1 ){
                result1 = dictionaryService.getDic("7","二级用户");
            }else{
                result1 = dictionaryService.getDic("6","一级用户");
            }
            JSONObject dic = JSON.parseObject(JSON.toJSONString(result1.getData()));
            String dicInfo = dic.getString("dicInfo");
            //当天打卡的所有任务
            int count=0;
            Result result2 = withdrawalService.cwListForPc(null, cusId, null, null, "到店打卡收入");
            System.out.println("result2 = " + result2);
            JSONArray array = JSONObject.parseArray(JSON.toJSONString(result2.getData()));
            System.out.println("array = " + array);
            if(array != null){
                for (Object o : array) {
                    Map map = (Map) o;
                    if(map.get("cwCreateTime").toString().substring(0,10).equals(date)){
                        count++;
                    }
                }
            }

            //每日打卡的次数未达到上限
            if(count < Integer.valueOf(dicInfo)){
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("cusId",cusId);
                jsonObject1.put("kgCoin",kgCoin + 1);
                customerService.cusEdit(jsonObject1);
                //增加流水
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("targetId",cusId);
                jsonObject2.put("targetReValue",kgCoin);
                jsonObject2.put("cwValue",1);
                jsonObject2.put("cwType",1);
                jsonObject2.put("cwInfo","到店打卡收入");
                jsonObject2.put("cwCreateTime",new Date());
                withdrawalService.cwAddSave(jsonObject2);
                //修改已签到状态
                for (MyMission myMission : myMissions) {
                    myMission.setSignState(1);
                    myMission.setSignDate(new Date());
                    myMissionMapper.updateById(myMission);
                }
                return Result.success();

            }else{
                return Result.fail(3,"每日打卡的次数已达到上限");
            }
        }
        return Result.fail(4,"今天在该商家已打卡");
    }

    @Override
    public void simpleSchedule() {
        List<Mission> list = this.baseMapper.selectMap();
        for (Mission mission : list) {
            if(mission.getLeftAmount() != null && mission.getLeftAmount().doubleValue() > 0){
                Result result = merchantService.getMerById(mission.getMerchantId());
                JSONObject merchant = JSON.parseObject(JSON.toJSONString(result.getData()));
                Result result1 = dictionaryService.getDic("26", "平台账户");
                JSONObject dictionary = JSON.parseObject(JSON.toJSONString(result1.getData()));
                if(mission.getSourceType()==0){
                    //退还商家的剩余赏金
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("merchantId",mission.getMerchantId());
                    jsonObject1.put("sendAmount",merchant.getDouble("sendAmount") - mission.getLeftAmount().doubleValue());
                    merchantService.merEdit(jsonObject1);
                    //增加商家流水
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("kwInfo","任务过期退款");
                    jsonObject3.put("sourceId",mission.getMerchantId());
                    jsonObject3.put("kwValue",mission.getLeftAmount().doubleValue());
                    jsonObject3.put("kwType",0);
                    jsonObject3.put("kwCreateTime",new Date());
                    jsonObject3.put("sourceReValue",merchant.getDouble("totalAmount")-merchant.getDouble("sendAmount"));
                    withdrawalService.kwAddSave(jsonObject3);
                }else {
                    //退还字典表中的"平台账户"的剩余赏金
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("dicId",26);
                    jsonObject1.put("dicInfo",Double.parseDouble(dictionary.getString("dicInfo")) + mission.getLeftAmount().doubleValue());
                    dictionaryService.editSave(jsonObject1);
                    //增加商家流水
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("kwInfo",merchant.getString("merchantName")+"商家,"+"任务过期退款");
                    jsonObject3.put("targetId",mission.getMerchantId());
                    jsonObject3.put("kwType",0);
                    jsonObject3.put("sourceId",null);
                    jsonObject3.put("targetReValue",Double.parseDouble(dictionary.getString("dicInfo")));
                    jsonObject3.put("kwValue",mission.getLeftAmount().doubleValue());
                    jsonObject3.put("kwCreateTime",new Date());
                    withdrawalService.kwAddSave(jsonObject3);
                }
                mission.setMissionState("D");
                this.baseMapper.updateById(mission);
            }
        }

    }

    @Override
    public boolean checkTitle(String merchantId, String missionTitle, String missionId) {
        LambdaQueryWrapper<Mission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Mission::getMerchantId,merchantId)
                .eq(Mission::getMissionTitle,missionTitle)
                .ne(missionId != null,Mission::getMissionId,missionId);
        List<Mission> list = list(wrapper);
        return list.size()==0?true:false;
    }

    @Override
    public Result miListByIds(String[] ids) {
        //获取token
        String token = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        token = token.substring(tokenHead.length());
        System.out.println("token = " + token);
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        String cusId = jsonObject.getString("username");
        List<Map> list = this.baseMapper.miListByIds(cusId,ids);
        if(list.size()==0){
            return Result.fail(ErrorCode.NODATA);
        }
        return Result.success(list);
    }
}




